package main

import (
	"context"
	"errors"
	"flag"
	"fmt"
	"gitee.com/Cookie_XiaoD/dna/core/snowflake"
	"gitee.com/Cookie_XiaoD/dna/server/rpc/pb"
	"google.golang.org/grpc"
	"google.golang.org/grpc/reflection"
	"google.golang.org/protobuf/types/known/emptypb"
	"log"
	"net"
	"os"
	"os/signal"
	"strconv"
	"syscall"
)

var (
	ipAddr    = flag.String("ipAddr", "127.0.0.1", "指定服务IP地址")
	port      = flag.String("port", "10000", "指定grpc服务端口")
	zkServers = flag.String("zkServers", "127.0.0.1:2181", "指定zookeeper服务地址，多个半角逗号分隔")
)

func main() {
	flag.Parse()
	errChan := make(chan error)
	go func() {
		errChan <- start()
	}()

	go func() {
		sign := make(chan os.Signal)
		signal.Notify(sign, syscall.SIGINT, syscall.SIGTERM)
		errChan <- errors.New("服务被结束" + (<-sign).String())
	}()

	log.Printf("%v\n", <-errChan)
}

func start() error {
	if err := snowflake.Init([]string{*zkServers}, snowflake.WithNodeEndpoint(*ipAddr+":"+*port)); err != nil {
		return fmt.Errorf("初始化失败:%w", err)
	}
	log.Println("初始化成功")

	lis, err := net.Listen("tcp", fmt.Sprintf(":%v", *port))
	if err != nil {
		return fmt.Errorf("打开TCP监听失败：%w", err)
	}
	grpcServer := grpc.NewServer()
	pb.RegisterIDGenServiceServer(grpcServer, &idGenServer{})
	reflection.Register(grpcServer)
	err = grpcServer.Serve(lis)
	if err != nil {
		return fmt.Errorf("开启服务失败：%w", err)
	}
	return nil
}

type idGenServer struct {
}

func (s *idGenServer) Get(ctx context.Context, empty *emptypb.Empty) (*pb.GenResp, error) {
	id, err := snowflake.GetID()
	if err != nil {
		return nil, err
	}
	return &pb.GenResp{Id: strconv.FormatUint(id, 10)}, nil
}
